﻿using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace program1
{
    public class Crawler
    {
        private Form1 mainForm;

        public Crawler(Form1 form)
        {
            mainForm = form;
        }

        public async Task Search(string keyword)
        {
            string searchEngineUrl = "https://www.baidu.com/s"; // 百度搜索引擎的URL
            string searchUrl = $"{searchEngineUrl}?wd={keyword}"; // 注意修改URL的参数名


            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    string searchResultHtml = await httpClient.GetStringAsync(searchUrl);
                    DataParser dataParser = new DataParser(mainForm);
                    dataParser.FindPhoneNumbers(searchResultHtml, searchUrl);
                }
            }
            catch (HttpRequestException ex)
            {
                if (ex.Message.Contains("404"))
                {
                    mainForm.DisplayErrorMessage("HTTP 404 - 页面未找到");
                }
                else
                {
                    mainForm.DisplayErrorMessage("HTTP请求异常：" + ex.Message);
                }
            }
            catch (Exception ex)
            {
                mainForm.DisplayErrorMessage("发生异常：" + ex.Message);
            }
        }
    }
}
